import requests
import datetime


def main():
    """
    主函数
    """
    #请求头
    header = {
        # 浏览器类型
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 '
                      'Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat '
    }
    #请求链接
    url = 'https://j1.pupuapi.com/client/product/storeproduct/detail/4dcdeca2-f5a3-4be8-9e2f-e099889a23a0/8eea11d0-c627-47e7-b0cd-6e1e1d57d187'
    data = cratchData(header, url)
    cratchPrint(data)
    listenPrice(header, url)


def cratchData(header, url):
    """
    爬取数据
    :param header:请求头
    :param url: 链接
    :return: 返回需要的数据
    """
    response = requests.get(url, headers=header).json()
    data = {}
    getData = response['data']  # 需要的数据
    data['name'] = getData['name']  # 名称
    data['spec'] = getData['spec']  # 规格
    data['price'] = str(getData['price'] / 100)  # 价格
    data['market_price'] = str(getData['market_price'] / 100)  # 原价
    data['content'] = getData['share_content']  # 详细内容
    return data


def cratchPrint(data):
    """
    打印爬取出来的数据
    :param data: 爬取出来的数据
    """
    print('---------------商品：' + data['name'] + '---------------')
    print('规格：' + data['spec'])
    print('价格：' + data['price'])
    print('原价/折扣价：' + data['price'] + "/" + data['market_price'])
    print('详细内容：' + data['content'] + '\n')
    print('---------------”' + data['name'] + '“价格波动---------------')


def listenPrice(header, url):
    """
    监听所爬取的商品
    :param header:请求头
    :param url: 请求链接
    """
    for priceFluctuation in range(1, 5):  # 多次请求查看价格波动
        data = cratchData(header, url)  # 调用“爬取数据”函数
        price = data['price']
        print('当前时间为' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ',价格为' + price)


main()
